package com.zjz.studynotes;

import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.zjz.studynotes.bean.StudyNoteInfo;
import com.zjz.studynotes.db.StudyNotesDb;

import java.util.List;

/**
 * Description: 笔记列表适配器
 * Author: zjz
 * Date:2025/5/5 14:16
 */
public class StudyNotesAdapter extends RecyclerView.Adapter<StudyNotesAdapter.NotesViewHolder> {

    private Context mContext;
    private List<StudyNoteInfo> mList;
    public StudyNotesAdapter(Context context, List<StudyNoteInfo> data) {
        mContext = context;
        mList = data;
    }

    @NonNull
    @Override
    public StudyNotesAdapter.NotesViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        return new NotesViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_notes, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull StudyNotesAdapter.NotesViewHolder holder, int position) {
        StudyNoteInfo info = mList.get(position);
        holder.mTvTitle.setText(info.getTitle());
        holder.mTvContent.setText(info.getContent());
        //点击删除数据
        holder.mTvDelete.setOnClickListener(view -> {
            StudyNotesDb.getInstance(mContext).getStudyNoteInfoDao().deleteNote(info);
            mList.remove(position);
            notifyItemRemoved(position);
        });

        //点击跳转编辑页面
        holder.mLyRoot.setOnClickListener(view -> {
            Intent intent = new Intent(mContext, EditActivity.class);
            intent.putExtra("info", info.getId());
            mContext.startActivity(intent);
        });
    }

    @Override
    public int getItemCount() {
        if (mList == null) {
            return 0;
        }
        return mList.size();
    }

    class NotesViewHolder extends RecyclerView.ViewHolder {
        public LinearLayout mLyRoot;
        public TextView mTvTitle;
        public TextView mTvContent;
        public TextView mTvDelete;
        public NotesViewHolder(@NonNull View itemView) {
            super(itemView);

            mLyRoot = itemView.findViewById(R.id.ly_root);
            mTvTitle = itemView.findViewById(R.id.tv_item_title);
            mTvContent = itemView.findViewById(R.id.tv_item_content);
            mTvDelete = itemView.findViewById(R.id.tv_item_delete);
        }
    }



}
